package com.example.niu.qqapp


import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.animation.AnimationSet
import com.example.niu.qqapp.adapter.ContactsPageListAdapter
import com.example.niu.qqapp.databinding.FragmentLoginBinding
import com.google.android.material.snackbar.Snackbar
import com.jakewharton.rxbinding2.view.RxView
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit



// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 *
 */
class LoginFragment : Fragment() {

    //新试view binding
    private var _binding: FragmentLoginBinding? = null
    private val binding get() = _binding!!

    private var fragmentListener: FragmentListener? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.textViewHistory.setOnClickListener {
            binding.layoutContext.visibility = View.INVISIBLE
            binding.layoutHistory.visibility = View.VISIBLE
            //创建3条历史记录菜单项，添加到layoutHistory中
            for (i in 0..2) {
                val layoutItem = activity!!.layoutInflater.inflate(
                    R.layout.login_history_item, null
                )
                //响应菜单项的点击，把它里面的信息填到输入框中。
                layoutItem.setOnClickListener {
                    binding.editTextQQNum.setText("123384328943894893")
                    binding.layoutContext.visibility = View.VISIBLE
                    binding.layoutHistory.visibility = View.INVISIBLE
                }
                binding.layoutHistory.addView(layoutItem)
            }

            //使用动画显示历史记录
            val set = AnimationUtils.loadAnimation(
                context,
                R.anim.login_history_anim
            ) as AnimationSet
            binding.layoutHistory.startAnimation(set)
        }

        //响应最外层View的点击事件，隐藏历史菜单
        view.setOnClickListener {
            if (binding.layoutHistory.visibility == View.VISIBLE) {
                binding.layoutContext.visibility = View.VISIBLE;
                binding.layoutHistory.visibility = View.INVISIBLE;
            }
        }

        //响应登录按钮的点击事件
        RxView.clicks(binding.buttonLogin)
            .throttleFirst(10, TimeUnit.SECONDS)
            .subscribe {
                //响应逻辑放这里，把onClick()中的代码移过来即可
                //取出用户名，向服务端发出登录请求。
                val username = binding.editTextQQNum.text.toString()
                val observable = fragmentListener!!.getChatServcie().requestLogin(username, null)
                observable.map { result ->
                    //判断服务端是否正确返回
                    if (result.retCode === 0) {
                        //服务端无错误，处理返回的数据
                        result.data
                    } else {
                        //服务端出错了，抛出异常，在Observer中捕获之
                        throw RuntimeException(result.errMsg)
                    }
                }.subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doFinally { fragmentListener?.hideProgressBar() }
                    .subscribe(object : Observer<ContactsPageListAdapter.ContactInfo?> {
                        override fun onSubscribe(d: Disposable) {
                            //准备好进度条
                            fragmentListener?.showProgressBar()
                        }

                        override fun onNext(contactInfo: ContactsPageListAdapter.ContactInfo) {
                            //保存下我的信息
                            MainActivity.myInfo = contactInfo

                            //无错误时执行,登录成功，进入主页面
                            val fragmentManager = activity!!.supportFragmentManager
                            val fragmentTransaction = fragmentManager.beginTransaction()
                            val fragment = MainFragment()
                            //替换掉FrameLayout中现有的Fragment
                            fragmentTransaction.replace(R.id.fragment_container, fragment)
                            fragmentTransaction.commit()
                        }

                        override fun onError(e: Throwable) {
                            //在这里捕获各种异常，提示错误信息
                            val errmsg = e.localizedMessage
                            Snackbar.make(binding.layoutContext, "大王祸事了：" + errmsg!!, Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show()
                            Log.e("qqserver", e.localizedMessage!!)
                        }

                        override fun onComplete() {}
                    })
            }

        //进入注册页面
        binding.textViewRegister.setOnClickListener {
            //启动注册Activity
            val intent = Intent(context, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is FragmentListener) {
            fragmentListener = context
        }
    }

    override fun onDetach() {
        super.onDetach()
        fragmentListener = null
    }
}
